package com.wangdao.wechatmall.controller.wx;

import com.wangdao.wechatmall.bean.bo.AuthLoginBO;
import com.wangdao.wechatmall.bean.vo.admin.BaseRespVo;
import com.wangdao.wechatmall.bean.vo.wx.WXLoginUserInfoVO;
import com.wangdao.wechatmall.bean.vo.wx.WXLoginVO;
import com.wangdao.wechatmall.realm.MallToken;
import com.wangdao.wechatmall.service.admin.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * wechat author
 * created by feng on 7/10/21
 */
@RestController
@RequestMapping("wx/auth")
public class WXAuthController {
    /**
     * 登录
     * created by feng on 7/10/21
     * <p>
     * 修改
     * created by zhangxiao on 7/12/21
     */

    @Autowired
    UserService userService;


    @PostMapping("login")
    public BaseRespVo login(@RequestBody AuthLoginBO authLoginBO) {
        Subject subject = SecurityUtils.getSubject();
        String username = authLoginBO.getUsername();
        String password = authLoginBO.getPassword();
        subject.getSession().setAttribute("username",username);

        MallToken mallToken = new MallToken(username, password, "wx");

        try {
            subject.login(mallToken);
        } catch (AuthenticationException e) {
            return BaseRespVo.fail("认证未通过");
        }
        WXLoginVO wxLoginVO = new WXLoginVO();
        Serializable id = subject.getSession().getId();
        wxLoginVO.setToken((String) id);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
        Date date = new Date();
        String format = simpleDateFormat.format(date);
        wxLoginVO.setTokenExpire(format);

        WXLoginUserInfoVO wxLoginUserInfoVO = new WXLoginUserInfoVO();
        wxLoginUserInfoVO = userService.selectUser(username);
        wxLoginVO.setUserInfo(wxLoginUserInfoVO);

        return BaseRespVo.ok(wxLoginVO);


    }

    @PostMapping("/logout")
    public BaseRespVo logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return BaseRespVo.ok();
    }

}